<template>
  <div id="menu-box" v-loading="isLoading">
    <el-card shadow="always" body-style="padding: 0">
      <el-menu
        v-if="!isLoading && !isFailed"
        ellipsis
        class="el-menu-top"
        mode="horizontal"
        :popper-offset="16"
        style="width: 100%"
        background-color="#e2e8f0"
        :default-active="String(data[1].id)"
      >
        <el-menu-item index="0" disabled style="font-weight: bolder; color: black; opacity: 1">
          大类别：
        </el-menu-item>

        <el-menu-item
          v-for="column in data"
          :key="column.id"
          :index="String(column.id)"
          @click="sendClickEvent(column.id)"
        >
          {{ column.name }}
        </el-menu-item>
      </el-menu>
      <el-empty v-else description="加载类别失败" :image-size="imageSize" style="height: 100px" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue"
import { getParentCategoriesApi } from "@/api/data-manager/categoryApi"
import { ElMessage } from "element-plus"
import emitter from "@/utils/mitt"

const emit = defineEmits(["clickColumn"])

const data = ref()

const isLoading = ref<boolean>(true)
const isFailed = ref<boolean>(false)

const imageSize: number = 50

const currentId = ref()

onMounted(() => {
  setTimeout(async () => {
    let res
    try {
      res = await getParentCategoriesApi()
    } catch (error) {
      ElMessage.error("类别数据加载失败，请稍后再试")
      isLoading.value = false
      isFailed.value = true
      return
    }
    res.data.unshift({
      id: "all",
      name: "全部"
    })
    data.value = res.data
    isLoading.value = false
    sendClickEvent(data.value[1].id)
  })
  emitter.on("DM:refresh", () => {
    emit("clickColumn", currentId.value)
  })
  emitter.on("DM:pcatrgory-change", async () => {
    let res
    res = await getParentCategoriesApi()
    if (!res.data) {
      return
    }
    data.value = res.data
    sendClickEvent(data.value[1].id)
  })
})

function sendClickEvent(id: any) {
  currentId.value = id
  emit("clickColumn", id)
}
</script>

<style lang="scss" scoped>
#menu-box {
  user-select: none;
  :deep(.el-menu-item:hover) {
    background-color: var(--color-gray-300);
  }
  :deep(.el-sub-menu__title:hover) {
    background-color: var(--color-gray-300);
  }
  :deep(.is-active) {
    background-color: inherit;
  }
}
</style>
